package com.foreveross.fetl.listener;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.concurrent.BlockingQueue;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.WebApplicationContext;

import com.mysql.jdbc.Driver;

public class JobListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		 WebApplicationContext webApplicationContext = (WebApplicationContext) arg0  
	                .getServletContext()  
	                .getAttribute(  
	                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 
		 	
		 
		 	try {
				ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) webApplicationContext
						.getBean("taskExecutor");
				
				BlockingQueue<Runnable> quere = taskExecutor.getThreadPoolExecutor().getQueue();
				
				if(null!=quere && quere.size()>0){
					for(Runnable run:quere){
						Thread t =new Thread(run);
						t.interrupt();
					//	taskExecutor.getThreadPoolExecutor().remove(run);
					}
				}
				taskExecutor.getThreadPoolExecutor().shutdownNow();
				System.out.println(taskExecutor.getThreadPoolExecutor().getCorePoolSize());
				System.out.println(quere.size());
			} catch (Exception e) {
				e.printStackTrace();
			}
		 	
		 	 Enumeration<java.sql.Driver> drivers = DriverManager.getDrivers();
		 	while (drivers.hasMoreElements()) {
	            Driver driver = (Driver) drivers.nextElement();
	            try {
	                DriverManager.deregisterDriver(driver);
	                System.out.println(String.format("deregistering jdbc driver: %s", driver));
	            } catch (SQLException e) {
	            	 System.out.println(String.format("deregistering jdbc driver: %s", driver));
	            	 e.printStackTrace();
	            }

	        }
		 	
			org.quartz.impl.StdScheduler startQuertz = (org.quartz.impl.StdScheduler) webApplicationContext  
	                .getBean("startQuertz");  
	        if(startQuertz != null && startQuertz.isStarted()) {  
	            startQuertz.shutdown();  
	        }  
	        
	        
	         try {
				CacheManager.getInstance().shutdown();
			} catch (CacheException e1) {
				e1.printStackTrace();
			}
	         
	         try {  
		            Thread.sleep(1000*10);  
		        } catch (InterruptedException e) {  
		            e.printStackTrace();  
		        }  
	       System.out.println("10S..");

		 }

}
